from fastapi import APIRouter, Depends, Form
from sqlalchemy.orm import Session
from typing import Optional, Dict, Any
from datetime import datetime
import json

from database import get_db
from services import data_service
import schemas

router = APIRouter()

# 统一响应格式
def create_response(code: int = 200, message: str = "成功", data: Any = None):
    return {
        "code": code,
        "message": message,
        "data": data
    }


@router.post("/upload", response_model=schemas.Response)
async def upload_data(
    merchant_id: int = Form(...),
    platform_type: str = Form(...),  # 平台类型
    merchant_name: str = Form(...),  # 商户名称
    data_period: str = Form(...),    # 数据周期
    json_data: str = Form(...),      # JSON格式的数据
    remark: Optional[str] = Form(None),
    db: Session = Depends(get_db)
):
    """
    上传JSON数据
    
    - **merchant_id**: 商户ID
    - **platform_type**: 平台类型
    - **merchant_name**: 商户名称
    - **data_period**: 数据周期
    - **json_data**: JSON格式的数据
    - **remark**: 备注信息
    """
    try:
        # 处理上传的数据
        data_service.process_upload_data(
            db=db,
            merchant_id=merchant_id,
            merchant_name=merchant_name,
            platform_type=platform_type,
            data_period=data_period,
            json_data=json_data
        )
        
        return create_response(
            message="数据上传成功",
            data={
                "merchantId": merchant_id,
                "platformType": platform_type,
                "dataPeriod": data_period,
                "uploadTime": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            }
        )
    except Exception as e:
        return create_response(code=500, message=f"数据上传失败: {str(e)}")


@router.get("/merchant", response_model=schemas.Response)
async def get_merchant_data(
    merchantId: int,
    templateId: Optional[int] = None,
    db: Session = Depends(get_db)
):
    """
    获取指定商户的数据
    
    - **merchantId**: 商户ID
    - **templateId**: 模板ID（可选），如果提供则使用模板格式化数据
    """
    try:
        data = data_service.get_merchant_data(db, merchantId, templateId)
        return create_response(
            message="获取数据成功",
            data=data
        )
    except Exception as e:
        return create_response(code=500, message=f"获取数据失败: {str(e)}")


@router.get("/merchants", response_model=schemas.Response)
async def list_merchants_with_data(
    name: Optional[str] = None,
    page_num: int = 1,
    page_size: int = 10,
    db: Session = Depends(get_db)
):
    """
    获取有数据的商户列表
    
    - **name**: 商户名称，支持模糊查询
    - **page_num**: 页码，从1开始，默认1
    - **page_size**: 每页记录数，默认10
    """
    try:
        filters = {
            "name": name
        }
        # 移除None值
        filters = {k: v for k, v in filters.items() if v is not None}
        
        result = data_service.get_merchant_list(db, filters, page_num, page_size)
        
        return create_response(
            message="查询成功",
            data=result
        )
    except Exception as e:
        return create_response(code=500, message=f"查询失败: {str(e)}") 